import React, { useEffect, useState, useCallback } from 'react';
import { Table, Divider, Modal, Form, Input, Select, Switch, Row, Col, Button, Tree , message, Radio, } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import RenderButtom from '@/components/RenderButton';
import MenuTree from '@/components/MenuTree';
import SearchBox from '@/components/SearchBox'
import MemberTree from './components/memberTree'
import {
  fetchPermission,
  saveOrUpdatePermission,
  deletePermission,
  addMenuPermission,
  addBtnPermission,
  addOperatePermission,
  getOnePermission,
  delMenuPermission,
  delBtnPermission,
  delOperateByPermission,
} from '@/services/merchants';
import {
  fetchMenus,
} from '@/services/menu'
import { connect } from 'dva';
import { formItemLayout } from '@/utils/utils'

const { confirm } = Modal;
const { Option } = Select;
const { TreeNode } = Tree;
const hasSearchBtn = JSON.parse(localStorage.getItem('hasSearchBtn'))

const columns = [
  {
    title: '权限',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '功能描述',
    dataIndex: 'describes',
    key: 'describes',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    render: text => <span>{text == 0 ? '启用' : '锁定'}</span>,
  },
];

const Privilege = props => {
  const { getFieldDecorator } = props.form;
  const { inform, radioGroup, selected } = props.role;
  const [data, setColData] = useState([]);
  const [otherId, setOtherId] = useState([]);
  const [permissionId, setPermissionId] = useState([])

  // 分配\新增 模态框
  const [isShow, setState] = useState(false);
  // 权限模态框
  const [visible, setVisible] = useState(false)
  // 按钮类型
  const [btnType, setBtnType] = useState(0)

  useEffect(() => {
    getList();
  }, []);

  // 列表
  const getList = useCallback(async params => {
    const r = await fetchPermission(params);
    setColData(r.data);
  }, []);

  // 查询
  const searchOnePermission = useCallback(async params => {
    const r = await getOnePermission(params);
    setColData(r.data);
  }, []);

  const removeRole = useCallback(async record => {
    const res = await deletePermission({
      id: record.id,
    });
    if (res.code == 0) {
      const index = data.findIndex(e => e.id == record.id);
      setColData(() => {
        data.splice(index, 1);
        return [...data];
      });
    }
  }, []);
  // 权限模态框
  const getPermissions = t => {
    if (t == 8) {
      props.dispatch({
        type: 'role/fetchMenusList',
        payload: {
          sys_permission_id: permissionId[0].id
        }
      }).then(() => setVisible(!visible))
      setOtherId([])
    }
    if (t == 9) {
      props.dispatch({
        type: 'role/fetchBtnsList',
        payload: {
          sys_permission_id: permissionId[0].id
        }
      }).then(() => setVisible(!visible))
      setOtherId([])
    }
    if (t == 10) {
      props.dispatch({
        type: 'role/fetchOperateList',
        payload: {
          sys_permission_id: permissionId[0].id
        }
      }).then(() => setVisible(!visible))
      setOtherId([])
    }
    return null
  }
  // 分配角色模态框
  const handleStatus = record => {
    setState(!isShow);
    if (record) {
      props.dispatch({
        type: 'role/changeModelState',
        payload: {
          inform: record,
        },
      });
    }
  };

  // 表单提交
  const handleSubmit = e => {
    e.preventDefault();
    props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
        const params = {
          ...inform,
          ...values,
          status: !!values.status ? 0 : 1,
        }
        btnType != 1 && Object.assign(params, {id: values.id ? values.id : inform.id})
        saveOrUpdatePermission(params).then(() => {
          getList()
          setState(!isShow);
        });
      }
    });
  };

  const handleCancel = () => {
    setState(!isShow);
    props.dispatch({
      type: 'role/changeModelState',
      payload: {
        inform: {},
      },
    });
  }

  // 查询表单
  const getFields = () => {
    return (
      <>
        <Col span={8}>
          <Form.Item label={`权限名称`}>
            {getFieldDecorator(`id`, {})(
            <Select
              showSearch
              filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
            >
              {data && data.map(r => <Option key={r.id} value={r.id}>{r.name}</Option>)}
            </Select>
            )}
          </Form.Item>
        </Col>
        {/* <MemberTree /> */}
      </>
    );
  };
  // 查询表单逻辑
  const handleSearch = e => {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      console.log('Received values of form: ', values);
      searchOnePermission({
        ...values,
      });
    });
  };

  // 清空查询条件
  const handleReset = () => {
    props.form.resetFields();
    getList()
  };

  // 按钮逻辑
  const handleBtn = t => {
    setBtnType(t)
    if (permissionId.length != 1 && t != 1) return message.warning('请选择一个权限！');
    switch (t) {
      case 1:
        return handleStatus()
      case 3:
        return handleStatus(permissionId[0])
      // 查询
      case 2:      
       return handleSearch();
      // 删除
      case 4:
       return removeRole(permissionId[0])
      // 配置权限
      case 8:
      case 9:
      case 10:
        return getPermissions(t)
      default:
        return null;
    }
  };

  // 权限新增处理
  const handlePermission = t => {
    if (t == 8) {
      addMenuPermission({
        sysPermissionId: permissionId[0].id,
        menuId: otherId,
      }).then(() => setVisible(!visible))
    }
    if (t == 9) {
      addBtnPermission({
        sysPermissionId: permissionId[0].id,
        elementId: otherId,
      }).then(() => setVisible(!visible))
    }
    if (t == 10) {
      addOperatePermission({
        sysPermissionId: permissionId[0].id,
        operationId: otherId,
      }).then(() => setVisible(!visible))
    }
  }

  // 权限删除处理
  const handleDelPermission = t => {
    if (t == 8) {
      delMenuPermission({
        sysPermissionId: permissionId[0].id,
        menuId: selected,
      }).then(() => setVisible(!visible))
    }
    if (t == 9) {
      delBtnPermission({
        sysPermissionId: permissionId[0].id,
        elementId: selected,
      }).then(() => setVisible(!visible))
    }
    if (t == 10) {
      delOperateByPermission({
        sysPermissionId: permissionId[0].id,
        operationId: selected,
      }).then(() => setVisible(!visible))
    }
  }

  const handlePermissionRadio = e => {
    if (selected && btnType != 8) return message.info('请先删除已选中权限')
    btnType == 8 ? setOtherId(e[0]) : setOtherId(e.target.value)
  }

  const rowSelection = {
    type: 'radio',
    onChange: (selectedRowKeys, selectedRows) => {
      setPermissionId(selectedRows)
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
  };
  const radioStyle = {
    display: 'block',
    height: '30px',
    lineHeight: '30px',
  };
  return (
    <PageHeaderWrapper>
      {/* 查询条件 */}
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <RenderButtom click={handleBtn} />
      <Table columns={columns} dataSource={hasSearchBtn ? data : []} rowSelection={rowSelection} rowKey={record => record.id} />
      {/* 新增/修改 */}
      <Modal
        title="新增/修改"
        visible={isShow}
        onOk={handleSubmit.bind(this)}
        onCancel={handleCancel.bind(this)}
        destroyOnClose
      >
        <Form {...formItemLayout}>
          <Form.Item label="权限名称">
            {getFieldDecorator('name', {
              initialValue: inform && inform.name,
              rules: [
                {
                  required: true,
                  message: '请输入角色名称',
                },
              ],
            })(<Input />)}
          </Form.Item>
          <Form.Item label="权限类型">
            {getFieldDecorator('type', {
              initialValue: inform && inform.type,
              rules: [
                {
                  required: true,
                  message: '请输入描述',
                },
              ],
            })(<Select>
                <Option value={1}>菜单权限</Option>
                <Option value={2}>页面元素权限</Option>
                <Option value={3}>功能操作权限</Option>
            </Select>)}
          </Form.Item>
          <Form.Item label="描述">
            {getFieldDecorator('describes', {
              initialValue: inform && inform.describes,
              rules: [
                {
                  required: false,
                  message: '请输入描述',
                },
              ],
            })(<Input />)}
          </Form.Item>
          <Form.Item label="状态">
            {getFieldDecorator('status', {
              initialValue: inform && !Number(inform.status) ? true : false,
              valuePropName: 'checked',
            })(<Switch />)}
          </Form.Item>
        </Form>
      </Modal>
      {/* 菜单权限 */}
      <Modal
        title="分配权限"
        visible={visible}
        onOk={handlePermission.bind(this, btnType)}
        onCancel={() => setVisible(!visible)}
        destroyOnClose
        footer={[
          <Button key="back" onClick={() => setVisible(!visible)}>
            取消
          </Button>,
          <Button type='danger' onClick={handleDelPermission.bind(this, btnType)}>
            删除
          </Button>,
          <Button key="submit" type="primary" onClick={handlePermission.bind(this, btnType)}>
            新增
          </Button>,
        ]}
      >
        {
          btnType == 8 ?
          <MenuTree 
            checkable={false}
            defaultSelectedKeys={[String(selected)] || [String(otherId)]}
            onSelect={handlePermissionRadio}
            defaultExpandAll={false}
            autoExpandParent={true}
            defaultExpandParent={true}
          /> :
          <Radio.Group value={selected || otherId} onChange={handlePermissionRadio}>
            {
              radioGroup && radioGroup.map(m => 
              <Radio key={m.id} style={radioStyle} value={m.id}>{m.name}</Radio>)
            }
          </Radio.Group >
        }
        
      </Modal>
    </PageHeaderWrapper>
  );
};
export default connect(({ role, global }) => ({
  role,
  hasSearchBtn: global.hasSearchBtn,
}))(Form.create()(Privilege));
